import {
  getCartList,
  getCartCounts,
  changeCartNum,
  cartDel
} from '../../api/cart.js';
import {
  getProductHot
} from '../../api/api.js';

const app = getApp();
const util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      'navbar': '1',
      'return': '0',
      'title': '购物车',
      'color': false
    },
    navH: 0,
    cartCount: 0,
    goodsHidden: true,
    footerswitch: true,
    cartList: {},
    isAllSelect: false, //全选
    selectValue: [], //选中的数据
    selectCountPrice: 0.00,
    isGoIndex: true,
    iShidden: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      navH: app.globalData.navHeight
    });
    if (app.globalData.token) that.setData({
      iShidden: true
    });
  },

  /**
   * 关闭授权
   * 
   */
  onCloseAuto: function() {
    this.setData({
      iShidden: true
    });
  },
  onLoadFun: function() {
    this.getCartList();
    this.getCartNum();
    this.getHotProduct();
  },
  /**
   * 删除购物车指定的商品
   */
  subDel: function(event) {
    var that = this,
      selectValue = that.data.selectValue;
    if (selectValue.length > 0)
      cartDel(selectValue).then(res => {
        that.getCartList();
        that.getCartNum();
      });
    else
      return app.Tips({
        title: '请选择产品'
      });
  },
  /**
   * 下单
   */
  subOrder: function(event) {
    var that = this,
      selectValue = that.data.selectValue;
    if (selectValue.length > 0) {
      wx.navigateTo({
        url: '/packageB/order_confirm/index?cartId=' + selectValue.join(',')
      });
    } else {
      return app.Tips({
        title: '请选择产品'
      });
    }
  },
  /**
   * 全选事件
   */
  checkboxAllChange: function(event) {
    var value = event.detail.value;
    console.log(value);
    if (value.length > 0) {
      this.setAllSelectValue(1)
    } else {
      this.setAllSelectValue(0)
    }
  },
  setAllSelectValue: function(status) {
    var that = this;
    var selectValue = [];
    var valid = that.data.cartList.valid;
    if (valid.length > 0) {
      for (var index in valid) {
        if (status == 1) {
          valid[index].checked = true;
          selectValue.push(valid[index].id);
        } else valid[index].checked = false;
      }
      var validData = "cartList.valid";
      that.setData({
        [validData]: valid,
        selectValue: selectValue,
      });
      that.switchSelect();
    }
  },
  checkboxChange: function(event) {
    var that = this;
    var value = event.detail.value;
    var valid = this.data.cartList.valid;
    for (var index in valid) {
      if (that.inArray(valid[index].id, value)) valid[index].checked = true;
      else valid[index].checked = false;
    }
    var validData = "cartList.valid";
    this.setData({
      [validData]: valid,
      isAllSelect: value.length == this.data.cartList.valid.length,
      selectValue: value,
    })
    this.switchSelect();
  },
  inArray: function(search, array) {
    for (var i in array) {
      if (array[i] == search) {
        return true;
      }
    }
    return false;
  },
  /**
   * 处理得出选择价格
   */
  switchSelect: function() {
    var that = this;
    var validList = that.data.cartList.valid;
    var selectValue = that.data.selectValue;
    var selectCountPrice = 0.00;
    if (selectValue.length < 1) {
      that.setData({
        selectCountPrice: selectCountPrice
      });
    } else {
      for (var index in validList) {
        if (that.inArray(validList[index].id, selectValue)) {
          selectCountPrice = Number(selectCountPrice) + Number(validList[index].num) * Number(validList[index].price)
        }
      }
      that.setData({
        selectCountPrice: selectCountPrice.toFixed(2)
      });
    }
  },
  /**
   * 扣减指定商品数量
   */
  subCart: function(event) {
    var that = this;
    var status = false;
    var index = event.currentTarget.dataset.index;
    var item = that.data.cartList.valid[index];
    item.num = item.num - 1;
    if (item.num < 1) status = true;
    if (item.num <= 1) {
      item.num = 1;
      item.numSub = true;
    } else {
      item.numSub = false;
      item.numAdd = false;
    }
    if (false == status) {
      that.setCartNum(item, 'SUB', function(data) {
        var itemData = "cartList.valid[" + index + "]";
        that.setData({
          [itemData]: item
        });
        that.switchSelect();
      });
    }
  },
  /**
   * 添加指定商品数量
   */
  addCart: function(event) {
    var that = this;
    var index = event.currentTarget.dataset.index;
    var item = that.data.cartList.valid[index];
    item.num = item.num + 1;
    if (item.num >= item.stock) {
      item.num = item.productInfo.stock;
      item.numAdd = true;
      item.numSub = false;
    } else {
      item.numAdd = false;
      item.numSub = false;
    }
    that.setCartNum(item, 'ADD', function(data) {
      var itemData = "cartList.valid[" + index + "]";
      that.setData({
        [itemData]: item
      });
      that.switchSelect();
    });
  },
  /**
   * 调用远程购物车修改商品数量方法
   */
  setCartNum(cart, flag, successCallback) {
    var that = this;
    changeCartNum(cart.id, cart.productId, flag).then(res => {
      successCallback && successCallback(res.data);
    });
  },
  /**
   * 获取商品数量
   */
  getCartNum: function() {
    var that = this;
    getCartCounts().then(res => {
      that.setData({
        cartCount: res.data
      });
    });
  },
  /**
   * 获取购物车列表
   */
  getCartList: function() {
    var that = this;
    getCartList().then(res => {
      var cartList = res.data;
      cartList.valid = cartList.valid||[];
      cartList.invalid = cartList.invalid||[];
      var valid = cartList.valid;
      var numSub = [{
        numSub: true
      }, {
        numSub: false
      }];
      var numAdd = [{
          numAdd: true
        }, {
          numAdd: false
        }],
        selectValue = [];;
      if (valid.length > 0) {
        for (var index in valid) {
          if (valid[index].num == 1) {
            valid[index].numSub = true;
          } else {
            valid[index].numSub = false;
          }
          if (valid[index].num == valid[index].stock) {
            valid[index].numAdd = true;;
          } else {
            valid[index].numAdd = false;
          }
          valid[index].checked = true;
          selectValue.push(valid[index].id);
        }
      }
      that.setData({
        cartList: cartList,
        goodsHidden: valid.length <= 0 ? false : true,
        selectValue: selectValue,
        isAllSelect: valid.length == selectValue.length && valid.length
      });
      that.switchSelect();
    });
  },
  goodsOpen: function() {
    var that = this;
    that.setData({
      goodsHidden: !that.data.goodsHidden
    })
  },
  manage: function() {
    var that = this;
    that.setData({
      footerswitch: !that.data.footerswitch
    })
  },
  /**
   * 获取热卖商品
   */
  getHotProduct: function() {
    var that = this;
    getProductHot().then(res => {
      that.setData({
        hot_product: res.data
      });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.isLog == true) {
      this.setData({
        goodsHidden: true,
        footerswitch: true,
        hot_product: [],
        cartList: {},
        isAllSelect: false, //全选
        selectValue: [], //选中的数据
        selectCountPrice: 0.00,
        cartCount: 0,
        iShidden: true
      });
      this.getCartList();
      this.getCartNum();
      this.getHotProduct();
    }
  },
  /**
   * 清空失效商品
   */
  unsetCart: function() {
    let that = this,
      ids = [];
    for (var i = 0, len = that.data.cartList.invalid.length; i < len; i++) {
      ids.push(that.data.cartList.invalid[i].id);
    }
    cartDel(ids).then(res => {
      app.Tips({
        title: '清除成功'
      });
      that.setData({
        'cartList.invalid': []
      });
    }).catch(res => {

    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

})